package dao.impl;

import bean.dto.OrderDto;
import bean.dto.OrderDto2;
import bean.pojo.Order;
import bean.pojo.Products;
import bean.vo.OrderInfoVo;
import bean.vo.OrderVo;
import commons.dbHelper.DBHelper;
import commons.xlhUtils.MyFormatUtils;
import dao.OrderDao;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * dao.impl
 * User: 李雨行
 * Date: 2024/12/18 14:52
 * motto:   沉淀哥
 * Description:
 * Version: V1.0
 */
public class OrderDaoImpl implements OrderDao {
    private static DBHelper dbHelper = new DBHelper();

    public String selectByOrderId(Integer orderId) {
        String orderInfo = "订单：";
        String sql = "SELECT p.product_name,p.price,opr.number " +
                "from orders o  " +
                "left join order_product_relation opr on o.order_id=opr.order_id " +
                "left join user u on o.user_id=u.user_id " +
                "join product p on p.product_id=opr.product_id " +
                "and o.order_id=? order by p.product_id desc";
        List<OrderInfoVo> list = dbHelper.getBeanList(OrderInfoVo.class, sql, orderId);
        for (OrderInfoVo orderInfoVo : list) {
            orderInfo=orderInfo.concat(orderInfoVo.getProductName()+ "*"+ orderInfoVo.getNumber() + " 单价:" + orderInfoVo.getPrice()   + "   ") ;
        }
        return orderInfo;
    }

    @Override
    public List<OrderVo> findByPage(Integer orderId, String userName, String productName, Integer page, Integer limit) {
        List<Object> list = new ArrayList<>();
        List<OrderVo> listVo =new ArrayList<>();
        if (productName == null && userName == null) {
            StringBuffer sql = new StringBuffer("SELECT o.order_id,u.user_name,o.total_amount,o.order_time,o.order_status " +
                    "from orders o  " +
                    "join user u on o.user_id=u.user_id and 1=1 ");
            if (orderId != null) {
                sql.append("and o.order_id=? ");
                sql.append(" order by o.order_id desc");
                sql.append(" limit "+(page-1)*limit+","+limit);
                list.add(orderId);
                OrderVo orderVo = dbHelper.getBean(OrderVo.class, sql.toString(), list.toArray());
                System.out.println(selectByOrderId(orderId));
                orderVo.setOrderInfo(selectByOrderId(orderId));
                listVo.add(orderVo);
                return listVo;
            }
            sql.append(" order by o.order_id desc ");
            sql.append(" limit "+(page-1)*limit+","+limit);
            List<OrderVo> listOrderVo = dbHelper.getBeanList(OrderVo.class, sql.toString(), list.toArray());
            for (OrderVo orderVo : listOrderVo) {
                    orderVo.setOrderInfo(selectByOrderId(orderVo.getOrderId()));
                    listVo.add(orderVo);
            }
            return listVo;
        } else {
            StringBuffer sql = new StringBuffer("SELECT o.order_id,u.user_name,o.order_time,o.total_amount,o.order_status  " +
                    "from orders o   " +
                    "left join order_product_relation opr on o.order_id=opr.order_id  " +
                    "join user u on o.user_id=u.user_id  " +
                    "join product p on p.product_id=opr.product_id  and 1=1 ");
            if (productName != null) {
                sql.append("and p.product_name like concat('%',?,'%')");
                list.add(productName);
            }
            if (userName != null) {
                sql.append("and u.user_name like concat ('%',?,'%')");
                list.add(userName);
            }
            if (orderId == null) {
                sql.append(" order by p.product_id desc");
                sql.append(" limit "+(page-1)*limit+","+limit);
                List<OrderVo> listOrderVo = dbHelper.getBeanList(OrderVo.class, sql.toString(), list.toArray());
                for (int i = 0; i < listOrderVo.size(); i++) {
                    if (i==0){
                        listOrderVo.get(i).setOrderInfo(selectByOrderId(listOrderVo.get(i).getOrderId()));
                        listVo.add(listOrderVo.get(i));
                    }else{
                        if (listOrderVo.get(i).getOrderId()!=listOrderVo.get(i-1).getOrderId()){
                            listOrderVo.get(i).setOrderInfo(selectByOrderId(listOrderVo.get(i).getOrderId()));
                            listVo.add(listOrderVo.get(i));
                        }
                    }
                }
//                for (OrderVo orderVo : listOrderVo) {
//                    orderVo.setOrderInfo(selectByOrderId(orderVo.getOrderId()));
//                    listVo.add(orderVo);
//                }
                return listVo;
            } else {
                List<OrderVo> listOrderVo = dbHelper.getBeanList(OrderVo.class, sql.toString(), list.toArray());
                for (OrderVo orderVo : listOrderVo) {
                    if (orderVo.getOrderId() == orderId) {
                        orderVo.setOrderInfo(selectByOrderId(orderId));
                        listVo.add(orderVo);
                    }
                }
                return listVo;
            }

        }
    }

    @Override
    public boolean add(OrderDto orderDto) {
        String sql3="select price from product where product_id=?";
        Products product = dbHelper.getBean(Products.class,sql3,orderDto.getProductId());
        Double amount=product.getPrice()*orderDto.getNumber();
        orderDto.setTotalAmount(amount);
        String sql="insert orders (user_id,order_time,total_amount,order_status) values(?,?,?,?)";
        Integer update=dbHelper.update(sql,orderDto.getUserId(),orderDto.getOrderTime(),orderDto.getTotalAmount(),orderDto.getOrderStatus());
        Order order=findId(orderDto);
        Integer id=order.getOrderId();
        String sql2="insert order_product_relation (order_id,product_id,number) values(?,?,?)";
        return dbHelper.update(sql2,id,orderDto.getProductId(),orderDto.getNumber())>0 && update>0;
    }



    public synchronized Order findId(OrderDto orderDto) {
        String sql="select order_id from orders where user_id=?  and total_amount=? and order_status=?";
        LocalDate localDate = orderDto.getOrderTime().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
        Date time= MyFormatUtils.localDateToDate(localDate );
        System.out.println(time);
        return dbHelper.getBean(Order.class,sql,orderDto.getUserId(),orderDto.getTotalAmount(),orderDto.getOrderStatus());
    }

    @Override
    public Integer maxPage(Integer orderId, String userName, String productName) {
        List<Object> list = new ArrayList<>();
        List<OrderVo> listVo =new ArrayList<>();
        if (productName == null && userName == null) {
            StringBuffer sql = new StringBuffer("SELECT o.order_id,u.user_name,o.total_amount,o.order_time,o.order_status " +
                    "from orders o  " +
                    "join user u on o.user_id=u.user_id and 1=1 ");
            if (orderId != null) {
                sql.append("and o.order_id=? ");
                sql.append(" order by o.order_id desc");
                list.add(orderId);
                OrderVo orderVo = dbHelper.getBean(OrderVo.class, sql.toString(), list.toArray());
                return 1;
            }
            sql.append(" order by o.order_id desc ");
            List<OrderVo> listOrderVo = dbHelper.getBeanList(OrderVo.class, sql.toString(), list.toArray());
            for (OrderVo orderVo : listOrderVo) {
                orderVo.setOrderInfo(selectByOrderId(orderVo.getOrderId()));
                listVo.add(orderVo);
            }
            return listVo.size();
        } else {
            StringBuffer sql = new StringBuffer("SELECT o.order_id,u.user_name,o.order_time,o.total_amount,o.order_status  " +
                    "from orders o   " +
                    "left join order_product_relation opr on o.order_id=opr.order_id  " +
                    "join user u on o.user_id=u.user_id  " +
                    "join product p on p.product_id=opr.product_id  and 1=1 ");
            if (productName != null) {
                sql.append("and p.product_name like concat('%',?,'%')");
                list.add(productName);
            }
            if (userName != null) {
                sql.append("and u.user_name like concat ('%',?,'%')");
                list.add(userName);
            }
            if (orderId == null) {
                sql.append(" order by p.product_id desc");
                List<OrderVo> listOrderVo = dbHelper.getBeanList(OrderVo.class, sql.toString(), list.toArray());
                for (int i = 0; i < listOrderVo.size(); i++) {
                    if (i==0){
                        listOrderVo.get(i).setOrderInfo(selectByOrderId(listOrderVo.get(i).getOrderId()));
                        listVo.add(listOrderVo.get(i));
                    }else{
                        if (listOrderVo.get(i).getOrderId()!=listOrderVo.get(i-1).getOrderId()){
                            listOrderVo.get(i).setOrderInfo(selectByOrderId(listOrderVo.get(i).getOrderId()));
                            listVo.add(listOrderVo.get(i));
                        }
                    }
                }
                return listVo.size();
            } else {
                List<OrderVo> listOrderVo = dbHelper.getBeanList(OrderVo.class, sql.toString(), list.toArray());
                for (OrderVo orderVo : listOrderVo) {
                    if (orderVo.getOrderId() == orderId) {
                        orderVo.setOrderInfo(selectByOrderId(orderId));
                        listVo.add(orderVo);
                    }
                }
                return listVo.size();
            }

        }
    }

    @Override
    public boolean deleteById(Integer orderId) {
        String sql1="delete from order_product_relation where order_id=?";

        String sql="delete from orders where order_id=?";
        return dbHelper.update(sql1,orderId)>0 && dbHelper.update(sql,orderId)>0;
    }

    @Override
    public boolean add2(OrderDto2 orderDto2) {
        String info=orderDto2.getOrderInfo();
        String [] arr = info.split(",");
        String [] name=new String [arr.length];
        String [] number=new String [arr.length];
        for (int i = 0; i < arr.length; i++) {
            String [] arr4=arr[i].split(":");
            name[i]=arr4[0];
//            System.out.println(name[0]);
            number[i]=arr4[1];
        }
        //获取产品总量
        int [] productNum=new int [arr.length];
        for (int i = 0; i < number.length; i++) {
            String sql="select stock from product where product_name=?";
//            System.out.println(name[i]);
            String n=name[i].replaceAll("\"","");
//            System.out.println(n);
            Products product = dbHelper.getBean(Products.class,sql,n);
            productNum[i]=product.getStock();
        }
        for (int i = 0; i < productNum.length; i++) {
            if (productNum[i]<Integer.parseInt(number[i])){
                return false;
            }
        }
        Double [] price=new Double [arr.length];
        for (int i = 0; i < number.length; i++) {
            String sql="select price from product where product_name=?";
//            System.out.println(name[i]);
            String n=name[i].replaceAll("\"","");
//            System.out.println(n);
            Products product = dbHelper.getBean(Products.class,sql,n);
            price[i]=product.getPrice();
        }
        Double amount=0.0;
        for (int i = 0; i < number.length; i++) {
            Integer num=Integer.valueOf(number[i]);
            amount+=num*price[i];
        }
        String sql="insert orders (user_id,order_time,total_amount,order_status) values(?,?,?,?)";
        Integer update=dbHelper.update(sql,orderDto2.getUserId(),orderDto2.getOrderTime(),amount,orderDto2.getOrderStatus());
        Order order=findId2(orderDto2,amount);
        Integer id=order.getOrderId();
        String sql1="insert order_product_relation (order_id,product_id,number) values(?,?,?)";
        int t=0;
        for (int i = 0; i < number.length; i++) {
            String na=name[i].replaceAll("\"","");
            sql="select product_id from product where product_name=?";
            Products products=dbHelper.getBean(Products.class,sql,na);
            t+=dbHelper.update(sql1,id,products.getProductId(),Integer.valueOf(number[i]));
        }
        for (int i = 0; i < productNum.length; i++) {
            sql="update product set stock=? where product_name=?";
            int num=productNum[i]-Integer.parseInt(number[i]);
            String na=name[i].replaceAll("\"","");
            dbHelper.update(sql,num,na);
        }
        return t==number.length;
    }

    @Override
    public boolean change(Integer orderId) {
        String sql="update orders set order_status=? where order_id=?";
        String sql1="select order_status from orders where order_id=?";
        Order order=dbHelper.getBean(Order.class,sql1,orderId);
        if (order.getOrderStatus().equals("接单")){
            return dbHelper.update(sql,"配送中",orderId)>0;
        }else if (order.getOrderStatus().equals("配送中")){
            return dbHelper.update(sql,"到达",orderId)>0;
        }else {
            return dbHelper.update(sql,"到达",orderId)>0;
        }
    }

    public  Order findId2(OrderDto2 orderDto2,Double amount) {
        String sql="select order_id from orders where user_id=?  and total_amount=? and order_status=?";
//        LocalDate localDate = orderDto2.getOrderTime().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
//        Date time= MyFormatUtils.localDateToDate(localDate );
//        System.out.println(time);
        return dbHelper.getBean(Order.class,sql,orderDto2.getUserId(),amount,orderDto2.getOrderStatus());
    }

}
